"""
    TorrentBrowser plugin for XBMC
    Copyright (C) 2011-2012 Markus Langenoja
    
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
import sys, string
try:
    __settings__ = sys.modules[ "__main__" ].__settings__
    __deb__ = sys.modules[ "__main__" ].__deb__
    get = __settings__.getSetting
except:
    __deb__ = False
    get = {}.get
    
def info2Xbmc():
    # Change this to modify what information should be parsed and sent to XBMC
    info = {'title':True,'plot':True,'duration':True,'mpaa':True,
            'rating':True,'genre':True,'premiered':True,'size':True,
            'year':True, 'director':True, 'writer':True, 'cast':True,
            'votes':True, 'aired':True}
    info['poster'] = get('poster') == 'true'
    info['backdrop'] = get('fanart') == 'true'
    return info

def getInfo(index):
    index = int(index)
    #===========================================================================
    # General Site info
    #===========================================================================
    site = (
            'TorrentLeech',
            'PassThePopcorn',
            'HDME',
            'SceneHD',
            'Funfile',
            'Demonoid',
            'SceneAccess',
            'RevolutionTT',
            'ZamundaNet',
            'ArenaBg'
            )
    baseUrl = (
                 'http://www.torrentleech.org',
                 'http://passthepopcorn.me',
                 'http://hdme.eu',
                 'http://scenehd.org',
                 'https://www.funfile.org',
                 'http://www.demonoid.me',
                 'http://sceneaccess.org',
                 'https://www.revolutiontt.net',
                 'http://zamunda.net',
                 'http://arenabg.com'
               )
    #===============================================================================
    # LOGIN PAGE & COOKIE INFORMATION
    #===============================================================================
    postUser = (
                'username',
                'username',
                'username',
                'username',
                'username',
                'nickname',
                'username',
                'username',
                'username',
                'username'
                )
    postPass = (
                'password',
                'password',
                'password',
                'password',
                'password',
                'password',
                'password',
                'password',
                'password',
                'password'
                )
    loginUrl =  (
                 'http://www.torrentleech.org/user/account/login/',
                 'http://passthepopcorn.me/login.php',
                 'http://hdme.eu/takelogin.php',
                 'http://scenehd.org/takelogin.php',
                 'https://www.funfile.org/takelogin.php',
                 'http://www.demonoid.me/account_handler.php',
                 'http://sceneaccess.org/login',
                 'https://www.revolutiontt.net/login.php',
                 'http://zamunda.net/takelogin.php',
                 'http://arenabg.com/'
                 )
    failedLogin = (
                   'Invalid Username/password combination',
                   'Your username or password was incorrect',
                   'Username or password incorrect',
                   'Your username or password was incorrect',
                   'Username or password incorrect',
                   'Erroneous password',
                   'Username or password incorrect',
                   'Login failed! Username or password incorrect.',
                   'Username or password incorrect',
                   'message error'
                   )
    cookie = (
              {'domain':'.torrentleech.org','check':'pass_hash'},
              {'domain':'passthepopcorn.me','check':'session'},
              {'domain':'hdme.eu','check':'pass'},
              {'domain':'.scenehd.org','check':'pass'},
              {'domain':'www.funfile.org','check':'pass'},
              {'domain':'.demonoid.me','check':'uhsh'},
              {'domain':'sceneaccess.org','check':'pass'},
              {'domain':'www.revolutiontt.net','check':'pass'},
              {'domain':'.zamunda.net','check':'pass'},
              {'domain':'.arenabg.com','check':'pass'}
              )
    
    #===========================================================================
    # Categories
    #===========================================================================
    
    cats =      (
                  {'title':'Open transmission add-on', 'catLabel':'TRANSMISSION'},
                  {'title':'Search','catlabel':'SEARCH'},
                  {'title':'Recently Added','catlabel':'BROWSEURL'},
                  {'title':'Most Snatched','catlabel':'SNATCHED'},
                  {'title':'Most Leeched','catlabel':'LEECHED'},
                  {'title':'Most Seeded','catlabel':'SEEDED'}                  
                  )
    categories = ( # just cats for all above categories supported on site
                  cats,
                  cats,
                  cats,
                  cats,
                  cats,
                  (cats[0],cats[1]),
                  cats,
                  cats,
                  cats,
                  cats
                  )
    
    #===========================================================================
    # General browse page information
    #===========================================================================
    browseUrl = (
                 'http://www.torrentleech.org/torrents/browse/index/categories/%s',
                 'http://passthepopcorn.me/torrents.php',
                 'http://hdme.eu/browse.php?%s',
                 'http://scenehd.org/browse.php?cat=%s',
                 'https://www.funfile.org/browse.php?%s',
                 'http://www.demonoid.me/files/?category=1&subcategory=0&language=0&quality=%s',
                 'http://sceneaccess.org/browse?%s',
                 'https://www.revolutiontt.net/browse.php?%s',
                 'http://zamunda.net/browse.php?%s',
                 'http://zamunda.net/torrents/%s')
    torrentsPerPage = (
                       100,
                       50,
                       15,
                       50,
                       25,
                       50,
                       25,
                       50,
                       20,
                       20
                       )
    nextPage = (
                # Default adjustment 0 makes page after first nmbr 2
                {'addon':'//index/page/','adj':0},
                {'addon':'&page=','adj':0},
                {'addon':'&page=','adj':-1},
                {'addon':'&page=','adj':-1},
                {'addon':'&page=','adj':-1},
                {'addon':'&page=','adj':0},
                {'addon':'&page=','adj':-1},
                {'addon':'&page=','adj':-1},
                {'addon':'&page=','adj':-1},
                {'addon':'/page:','adj':0}
               )
    topSnatch = (
                 'http://www.torrentleech.org/torrents/browse/index/facets/b4677b/categories/%s/orderby/completed/order/desc',
                 'http://passthepopcorn.me/torrents.php?order_way=desc&order_by=snatched&',
                 'http://hdme.eu/browse.php?sort=times_completed&d=DESC&%s',
                 'http://scenehd.org/browse.php?sort=6&cat=%s',
                 'https://www.funfile.org/browse.php?%s&sort=6&type=desc',
                 '',
                 'http://sceneaccess.org/browse?%s&sort=5&type=desc',
                 'https://www.revolutiontt.net/browse.php?%s&sort=6&type=desc',
                 'http://zamunda.net/browse.php?%s&sort=6&type=desc',
                 'http://arenabg.com/torrents/%s/sort:completed/'
                 )
    topLeech = (
                 'http://www.torrentleech.org/torrents/browse/index/facets/b4677b/categories/%s/orderby/leechers/order/desc',
                 'http://passthepopcorn.me/torrents.php?order_way=desc&order_by=leechers&',
                 'http://hdme.eu/browse.php?sort=leechers&d=DESC&%s',
                 'http://scenehd.org/browse.php?sort=8&cat=%s',
                 'https://www.funfile.org/browse.php?%s&sort=8&type=desc',
                 '',
                 'http://sceneaccess.org/browse?%s&sort=7&type=desc',
                 'https://www.revolutiontt.net/browse.php?%s&sort=8&type=desc',
                 'http://zamunda.net/browse.php?%s&sort=10&type=desc',
                 'http://arenabg.com/torrents/%s/sort:leechers/'                 
                 )
    topSeed = (
                 'http://www.torrentleech.org/torrents/browse/index/facets/b4677b/categories/%s/orderby/seeders/order/desc',
                 'http://passthepopcorn.me/torrents.php?order_way=desc&order_by=seeders&',
                 'http://hdme.eu/browse.php?sort=seeders&d=DESC&%s',
                 'http://scenehd.org/browse.php?sort=7&cat=%s',
                 'https://www.funfile.org/browse.php?%s&sort=7&type=desc',
                 '',
                 'http://sceneaccess.org/browse?%s&sort=6&type=desc',
                 'https://www.revolutiontt.net/browse.php?%s&sort=7&type=desc',
                 'http://zamunda.net/browse.php?%s&sort=9&type=desc',
                 'http://arenabg.com/torrents/%s/sort:seeders/'             
                 )
    
    searchUrl = (
                 'http://www.torrentleech.org/torrents/browse/index/categories/%s/query/',
                 'http://passthepopcorn.me/torrents.php?searchstr=',
                 'http://hdme.eu/browse.php?%s&search=',
                 'http://scenehd.org/browse.php?cat=%s&search=',
                 'https://www.funfile.org/browse.php?%s&incldead=0&search=',
                 'http://www.demonoid.me/files/?category=1&subcategory=All&quality=All&seeded=0&external=2&uid=0&sort=S&query=',
                 'http://sceneaccess.org/browse?%s&method=2&search=',
                 'https://www.revolutiontt.net/browse.php?titleonly=1&%s&search=',
                 'http://zamunda.net/browse.php?%s&search=',
                 'http://arenabg.com/torrents/%s/search:'
                 )
    
    detailsUrl = (
                 '',
                 '',
                 '',
                 '',
                 '',
                 '',
                 '',
                 '',
                 'http://zamunda.net/details.php?id=',
                 'http://arenabg.com/torrents/'
                 )
        
    search = (
                 {'check':False,'url':addCats(index,searchUrl[index]),'re':'There are no results found, based on your search parameters. Please refine your search.'},
                 {'check':'<title>Browse Torrents :: PassThePopcorn</title>','url':addCats(index,searchUrl[index]),'re':'<h2>Your search did not match anything.</h2>','idregexp':'var groupid=(\d+?)\;'},
                 {'check':False,'url':addCats(index,searchUrl[index]),'re':'<h2>Nothing found!</h2>'},
                 {'check':False,'url':addCats(index,searchUrl[index]),'re':'<h2>No torrents found!</h2>'},
                 {'check':False,'url':addCats(index,searchUrl[index]),'re':'<h2>Nothing found!</h2>'},
                 {'check':False,'url':addCats(index,searchUrl[index]),'re':'No torrents found'},
                 {'check':False,'url':addCats(index,searchUrl[index]),'re':'Nothing found!'},
                 {'check':False,'url':addCats(index,searchUrl[index]),'re':'Nothing found!'},
                 {'check':False,'url':addCats(index,searchUrl[index]),'re':'Nothing found!'},
                 {'check':False,'url':addCats(index,searchUrl[index]),'re':'Nothing found!'}
              )
    
    #===========================================================================
    # RegExps for finding movies (Torrent-ID, Title, IMDBiD, DLUrl, SubDlUrls, MagnetUrl)
    #===========================================================================
    regExp = (   
                 {'pos':(0,1,None,2,None,None),'re':'<a href="/torrent/(.+?)">(.+?)</a></span><br>\\n\\t\\t\\t.+?<b>.+?</b>.+?</td>\\n\\t\\t\\t<td class="quickdownload">\\n.+?<a href="(.+?)"'},
                 {'pos':(0,1,2,None,None,None),'re':'<a href="torrents.php\?id=(.+?)" onclick="Previewsrc\(\\\'.+?\\\',\\\'.+?\\\'\);"><img src=".+?" alt="" title=".+?" width="117"></a>\\n\\t\\t\\t\\n\\t\\t</td>\\n\\t\\t<td colspan="2">\\n\\t\\t\\t<a href="torrents.php\?id=.+?" title="View Torrent">(.+?)</a>.+?\\t\\t\\t<span style="float:right;"><a href="#" id=".+?" onclick="Bookmark\(.+?,\\\'Unbookmark\\\', 0\);return false;">Bookmark</a></span>\\n\\t\\t\\t<br />\\n\\t\\t\\t<div class="tags" style="padding:2px">\\n\\t\\t\\t\\t<div class="browserating"><span class="imdbtitle"><a target="_blank" href="http://imdb.com/title/tt(.+?)">IMDb</a>'},
                 {'pos':(0,1,None,2,None,None),'re':'<a href="details.php\?id=(.+?)\&amp;.+?" title="(.+?)">.*?\\n.*?\\n.*?\\n.*?\\n.*?\\n.*?\\n.*?\\n.*?\\n.*?<a href=(download.php\?.+?)>'},
                 {'pos':(1,2,0,3,None,None),'re':'<a href="http://www.imdb.com/title/tt(.+?)/" target="_blank">.*?<a href="details.php\?id=(.+?)" title="(.+?)">.*?\\n.*?<a href=(download.php\?.+?)>'},
                 {'pos':(0,1,None,2,None,None),'re':'<nobr><a style="float: left; vertical-align: middle; font-weight: bold;" href="details.php\?id=(.+?)\&amp;hit=1" title="(.+?)"><b>.+?</b></a>\\n</nobr><br /><a style="float: left;; margin:3px 3px 0 0" href="javascript: klappe_trt\(\'.+?\'\)"><img border="0" src="pic/plus.gif" id=".+?" alt="Show/Hide" /></a>\n</td>\n<td class=".+?" style="text-align: center;"><a href="(.+?)">'},
                 {'pos':(0,1,None,2,None,None),'re':'<td colspan="9" class=".+?"><a href="(/files/details.+?)">(.+?)</a>.*?</td>.*?\\n.+?\\n.+?\\n.+?\\n.+?\\n.+?\\n.*?\\n.+?a href="(/files/download.+?)"'},
                 {'pos':(0,1,None,2,None,None),'re':'<a href="details\?id=(.+?)" title="(.+?)">.+?\\n.+?<a href="(download/.+?)">'},
                 {'pos':(0,1,None,2,None,None),'re':'<td align=left nowrap class=br_right><a href="details.php\?id=(.+?)\&amp.+?<b>(.+?)</b>.+?\\n</td>\\n.+?\\n.+?a href="(download.php.+?)"><img width=14 src=/pic/download.gif border=0 alt=Download title=Download></a></td>\\n<td align="center">.+?</td>'},
                 {'pos':(0,3,4,1,5,2),'re':'<a href="details.php\?id=(.+?)\&amp;.+?".+?title=".+?">.*?\\n.*?<a href="(download.php.+?)">.*?<a href=["\'\s](magnet.*?)["\'\s]>'},
                 {'pos':(0,1,2,3,4,5),'re':'<td valign="top".*?<a href="/torrents/(\d+)/" onmouseover=".*?" onmouseout=".*?".*?>(.+?)</a>\s*?<div'}
                 )
        
    #If we can't get some information from the list page, we can try to get it from the details page. The items in this list are appended to the found items from the regExp, so adjust their position in the regExp 'pos' 
    detailsRegExp = (
                 [],
                 [],
                 [],
                 [],
                 [],
                 [],
                 [],
                 [],
                 ['download.php.+?>(.+?).torrent','href="http://www.imdb.com/title/tt(.+?)/"', ['href=.*?(http.*?subsunacs.net.*?)["\s]', 'href=.*?(http.*?subs.sab.bz.*?)["\s]', 'href=.*?(http.*?zamunda.net/getsubs.*?)["\s]'] ],
                 ['href="http://www.imdb.com/title/tt(.+?)/"', '<a href="(/torrents/.*?/.*?/)".*?class="button large download"', ['href=.*?(http.*?subsunacs.net.*?)["\s]', 'href=.*?(http.*?subs.sab.bz.*?)["\s]'], '<a href=["\'\s](magnet.*?)["\'\s]>'])
    
    #Describes if the subtitles needs to be scraped from their own details page and how their download link should be scraped in their details page
    #The special string (torrent-site-internal-subs) is indicating that the subtitles are within the torrent site and maybe this will require login credentials to be passed as cookies
    subtitleDetailsRegExp = (
                 [],
                 [],
                 [],
                 [],
                 [],
                 [],
                 [],
                 [],
                 ['href="(get.php.+?)"', 'href="(.*?subs.sab.bz.*?act=download.*?sid=.*?attach_id.*?)"', '(torrent-site-internal-subs)'],
                 ['href="(get.php.+?)"', 'href="(.*?subs.sab.bz.*?act=download.*?sid=.*?attach_id.*?)"'])
    #===========================================================================
    # Format RegExp (DLUrl, Format, Filname)
    #===========================================================================
    format  = ( # POS = (DlURL, Format, Filename)
               {'formats':False},
               {'formats':True,'dlurlindex':0,'iconindex':1,'formatindex':2,'filenameindex':3,'browseUrl':'http://passthepopcorn.me/torrents.php?id=%s','re':'<a href="(.+?)" title="Download">DL</a>.*?\\n.*?\\n.*?\\n.*?\\n.*?src="(.+?)".*?return false;">(.+?)</a>.*?\\n.*?\\n.*?\\n.*?\\n.*?\\n.*?\\n.*?\\n.*?\\n.*?\\n.*?\\n.*?\\n.*?\\n.*?\\n.*?\\n.*?\\n.*?\\n.*?\\n.*?\\n.*?\\n.*?Size.*?<tr><td>(.+?)\.\w\w\w</td>'},
               {'formats':False},
               {'formats':False},
               {'formats':False},
               {'formats':False},
               {'formats':False},
               {'formats':False},
               {'formats':False},
               {'formats':False}
               )
    #===========================================================================
    # Debuging and returning
    #===========================================================================
    if __deb__:
        print postUser[index]
        print postPass[index]
        print loginUrl[index]
        print browseUrl[index]
        print topSnatch[index]
        print topLeech[index]
        print topSeed[index]
        print search[index]
        print regExp[index]
        print nextPage[index]
        print torrentsPerPage[index]
        print format[index]
        print site[index]
        print baseUrl[index]
        print failedLogin[index]
        print categories[index]
        
    return {
            'POSTUSER':postUser[index],'POSTPASS':postPass[index],'LOGINURL':loginUrl[index],
            'BROWSEURL':addCats(index,browseUrl[index]),'SNATCHED':addCats(index,topSnatch[index]),
            'LEECHED':addCats(index,topLeech[index]),'SEEDED':addCats(index,topSeed[index]),
            'SEARCH':search[index],'REGEXP':regExp[index],'NEXTPAGE':nextPage[index],
            'TORRENTSPERPAGE':torrentsPerPage[index],'FORMATS':format[index],'SITE':site[index],
            'BASEURL':baseUrl[index],'FAILED':failedLogin[index],'CATEGORIES':categories[index],
            'COOKIE':cookie[index], 'DETAILS':detailsUrl[index], 'DETAILSREGEXP':detailsRegExp[index],
            'SUBDETAILREGEXP':subtitleDetailsRegExp[index], 'USERNAME':getUserNameAndPassword(index)[0],
            'PASSWORD':getUserNameAndPassword(index)[1]
            }
    
def addCats(index,url):
    # This function is to create the correct urls depending on settings.
    cat = []
    
    if index == 0: #TorrentLeech
        if get('tldvdrip') == "true":
            cat.append('11')
        if get('tlr5') == "true":
            cat.append('10')
        if get('tlhd') == "true":
            cat.append('13')
        if get('tlbd') == "true":
            cat.append('14')
        url = url % (string.join(cat,'%2C'))
        
    elif index == 1: #PTP
        url = url
        
    elif index == 2: #HDME
        if get('hdme720') == "true":
            cat.append('c32=1')
        if get('hdme1080i') == "true":
            cat.append('c30=1')
        if get('hdme1080p') == "true":
            cat.append('c31=1') 
        url = url % (string.join(cat,'&'))
        
    elif index == 3: #SceneHD
        if get('scenehd720') == "true":
            cat.append('4')
        if get('scenehd1080') == "true":
            cat.append('1')
        url = url % (string.join(cat,'%2C'))
        
    elif index == 4: #Funfile
        if get('funfileanime') == "true":
            cat.append('c44=1')
        if get('funfilemovies') == "true":
            cat.append('c19=1')
        url = url % (string.join(cat,'&'))
        
    elif index == 5: # Demonoid
        index = get('demonformat')
        if index == 1:
            cat = 66
        if index == 0:
            cat = 9
        if index == 2:
            cat = 68
        url = url % (str(cat))
    
    elif index == 6: # SceneAccess
        if get('sccsd') == "true":
            cat.append('c7=7')
        if get('scchd') == "true":
            cat.append('c22=22')
        url = url % (string.join(cat,'&'))
        
    elif index == 7: # RevolutionTT
        if get('revdvdr') == 'true':
            cat.append('c20=1')
        if get('revpacks') == 'true':
            cat.append('c44=1')
        if get('revx264') == 'true':
            cat.append('c10=1')
        if get('revxvid') == 'true':
            cat.append('c19=1')
        url = url % (string.join(cat,'&'))
        
    elif index == 8: #Zamunda.net
        if get('zamundatvserial') == 'true':
            cat.append('c7=1')
        if get('zamundasporthd') == 'true':
            cat.append('c43=1')
        if get('zamundasporttv') == 'true':
            cat.append('c41=1')            
        if get('zamundafilmshdtv') == 'true':
            cat.append('c5=1')
        if get('zamundafilmsxvid') == 'true':
            cat.append('c19=1')
        if get('zamundafilmsbg') == 'true':
            cat.append('c24=1')
        if get('zamundafilmsscience') == 'true':
            cat.append('c31=1')
        if get('zamundafilmsrussia') == 'true':
            cat.append('c28=1')
        if get('zamundahdtv') == 'true':
            cat.append('c33=1')
        if get('zamundax264') == 'true':
            cat.append('c35=1')
        url = url % (string.join(cat,'&'))
        
    elif index == 9: #ArenaBg
        
        categories = ['', 
                      'type:xvid', 
                      'type:hdtv', 
                      'type:x264', 
                      'type:tvepisodes', 
                      'type:tvboxset', 
                      'type:documentaries', 
                      'type:boxset', 
                      'type:x264boxset', 
                      'type:tvepisodeshd', 
                      'type:tvboxsethd', 
                      'type:arenabgtv']
        
        categoryFilterIndex = int(get('arenabg_category_filter'))
        cat.append(categories[categoryFilterIndex])
        
        url = url % (string.join(cat,'/'))
        
    return url
            
def getUserNameAndPassword(index):
                    
    if index == 0: #TorrentLeech
        return ( get('tlusername'), get('tlpassword') )
        
    elif index == 1: #PTP
        return ('', '')
        
    elif index == 2: #HDME        
        return ( get('hdmeusername'), get('hdmepassword') )
    
    elif index == 3: #SceneHD
        return ( get('scenehdusername'), get('scenehdpassword') )
        
    elif index == 4: #Funfile
        return ( get('funfileusername'), get('funfilepassword') )
        
    elif index == 5: # Demonoid
        return ( get('demonusername'), get('demonpassword') )
    
    elif index == 6: # SceneAccess
        return ( get('sccusername'), get('sccpassword') )
    
    elif index == 7: # RevolutionTT
        return ( get('revusername'), get('revpassword') )
        
    elif index == 8: #Zamunda.net
        return ( get('zamundausername'), get('zamundapassword') )
        
    elif index == 9: #ArenaBg        
        return ( get('arenausername'), get('arenapassword') )        